const path = require('path');
const fs = require('fs');
const multer = require('multer');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../public/images');
if (!fs.existsSync(path.join(__dirname, '../../public'))) {
  fs.mkdirSync(path.join(__dirname, '../../public'));
}
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 配置存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, uniqueSuffix + ext);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只接受图片文件
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件'), false);
  }
};

const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
});

/**
 * 图片控制器
 */
const imageController = {
  /**
   * 上传图片
   */
  uploadImage: (req, res) => {
    try {
      if (!req.file) {
        return res.status(400).json({
          code: 0,
          msg: '未上传文件或文件类型不正确',
          data: null
        });
      }
      // 返回图片完整URL
      const imagePath = `/images/${req.file.filename}`;
      // const fullUrl = `${req.protocol}://${req.get('host')}${imagePath}`;
      // TODO:暂时写死
      const fullUrl = `${req.protocol}://192.168.3.16:3000${imagePath}`;
      
      res.json({
        code: 1,
        msg: 'success',
        data: {
          url: fullUrl
        }
      });
    } catch (error) {
      console.error('上传图片出错:', error);
      res.status(500).json({
        code: 0,
        msg: '上传图片失败',
        data: null
      });
    }
  },

  // 获取上传中间件
  getUploadMiddleware: () => upload.single('file')
};

module.exports = imageController;